// JwtInterceptor.java
package com.qk.manangement.interceptor;

import com.qk.common.properties.JwtProperties;
import com.qk.common.utils.JwtUtils;
import com.qk.common.context.UserContext;
import com.qk.entity.pojo.User;
import com.qk.common.response.Result;
import com.qk.manangement.mapper.UserMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * JWT认证拦截器
 * 用于拦截请求并验证JWT token，将用户信息存储到UserContext中
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtils jwtUtils;

    // 不需要认证的路径前缀
    private static final String[] EXCLUDE_PATHS = {
        "/login",
        "/register",
        "/swagger",
        "/v2/api-docs"
    };
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        
        // 获取请求路径
        String requestURI = request.getRequestURI();
        
        // 检查是否为排除路径
        for (String excludePath : EXCLUDE_PATHS) {
            if (requestURI.startsWith(excludePath)) {
                return true;
            }
        }
        
        // 从请求头中获取token
        String token = request.getHeader("token");
        
        // 如果没有token，返回401统一格式错误
        if (token == null || token.isEmpty()) {
            return handleUnauthorized(response, "缺少认证令牌");
        }
        
        // 处理Bearer token格式
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        try {
            // 验证并解析token
            if (!jwtUtils.validateToken(token)) {
                return handleUnauthorized(response, "令牌无效或已过期");
            }
            
            // 解析token获取用户信息
            Claims claims = jwtUtils.parseToken(token);
            String username = (String) claims.get("username");
            
            if (username == null) {
                return handleUnauthorized(response, "令牌中缺少用户名信息");
            }
            
            User user = userMapper.getByUsername(username);
            if (user == null) {
                return handleUnauthorized(response, "用户不存在");
            }
            
            // 将用户信息存储到UserContext中
            UserContext.setUser(user);
            
            return true;
        } catch (ExpiredJwtException e) {
            return handleUnauthorized(response, "令牌已过期");
        } catch (SignatureException e) {
            return handleUnauthorized(response, "令牌签名验证失败");
        } catch (MalformedJwtException e) {
            return handleUnauthorized(response, "令牌格式错误");
        } catch (Exception e) {
            return handleUnauthorized(response, "令牌解析失败: " + e.getMessage());
        }
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                                Object handler, Exception ex) throws Exception {
        // 请求完成后清理UserContext，防止内存泄漏
        UserContext.clear();
    }
    
    /**
     * 处理未授权响应，使用统一返回格式
     * 
     * @param response HttpServletResponse对象
     * @param message 错误信息
     * @return false表示拦截处理完成
     * @throws IOException IO异常
     */
    private boolean handleUnauthorized(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        
        // 使用Result统一返回格式
        Result result = Result.error(message);
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(result));
        
        return false;
    }
}
